<template>
  <NavBar></NavBar>
  <div class="location-container">
    <div class="location-box">
      <div class="search-title">位置轨迹查询</div>
      <el-form :model="form" @submit.prevent="handleSearch">
        <el-form-item>
          <el-input
              v-model="form.searchParam"
              placeholder="输入牛耳标或牛ID..."
              style="max-width: 600px"
              class="input-with-select"
          >
            <template #append>
              <el-button type="primary" :icon="Search" native-type="submit" />
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <div v-if="currentCattle" class="cattle-info">
        <el-descriptions title="牛只信息" border>
          <el-descriptions-item label="耳标">{{ currentCattle.earTag }}</el-descriptions-item>
          <el-descriptions-item label="名称">{{ currentCattle.name }}</el-descriptions-item>
          <el-descriptions-item label="最后位置">
            {{ currentCattle.latitude ? `${currentCattle.latitude}, ${currentCattle.longitude}` : '暂无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div v-loading="loading" class="data-container">
        <div id="map-container"></div>
        <el-alert v-if="locationData.length === 0" title="暂无位置数据" type="info" />
      </div>

      <nav aria-label="..." class="pagination-container">
        <ul class="pagination">
          <li class="page-item" :class="{ disabled: currentPage === 1 }" @click="clickPage(-1)">
            <a class="page-link" href="javascript:void(0)">上一页</a>
          </li>
          <li
              v-for="page in pages"
              :key="page"
              class="page-item"
              :class="{ active: page === currentPage }"
              @click="clickPage(page)"
          >
            <a class="page-link" href="javascript:void(0)">{{ page }}</a>
          </li>
          <li class="page-item" :class="{ disabled: currentPage === totalPages }" @click="clickPage(-2)">
            <a class="page-link" href="javascript:void(0)">下一页</a>
          </li>
        </ul>
      </nav>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, onBeforeUnmount, nextTick } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import NavBar from '@/components/NavBar.vue'
import { Search } from '@element-plus/icons-vue'

export default {
  components: { NavBar },
  setup() {
    const store = useStore()
    const route = useRoute()
    const form = reactive({ searchParam: '' })
    const locationData = ref([])
    const currentCattle = ref(null)
    const loading = ref(false)
    const mapInstance = ref(null)
    const BMapGL = ref(null)

    const currentPage = ref(1)
    const pageSize = 8
    const total = ref(0)
    const totalPages = computed(() => Math.ceil(total.value / pageSize))
    const pages = computed(() => {
      const start = Math.max(1, currentPage.value - 2)
      const end = Math.min(totalPages.value, currentPage.value + 2)
      return Array.from({ length: end - start + 1 }, (_, i) => start + i)
    })

    const loadBMap = () => {
      return new Promise((resolve, reject) => {
        if (typeof window.BMapGL !== 'undefined') {
          resolve(window.BMapGL)
          return
        }
        window.onBMapCallback = function () {
          resolve(window.BMapGL)
        }
        const script = document.createElement('script')
        script.src = `https://api.map.baidu.com/api?type=webgl&v=1.0&ak=C8ecEy53EQWJaBz2aSqpcPk8EM15ToIn&callback=onBMapCallback`
        script.onerror = reject
        document.head.appendChild(script)
      })
    }

    const createCustomIcon = (cattle) => {
      return new Promise((resolve) => {
        const size = 40
        const img = new Image()
        img.crossOrigin = 'anonymous'

        img.onload = () => {
          const canvas = document.createElement('canvas')
          canvas.width = size
          canvas.height = size
          const ctx = canvas.getContext('2d')

          ctx.beginPath()
          ctx.arc(size / 2, size / 2, size / 2, 0, Math.PI * 2)
          ctx.closePath()
          ctx.clip()

          const ratio = Math.min(size / img.width, size / img.height)
          ctx.drawImage(
              img,
              (size - img.width * ratio) / 2,
              (size - img.height * ratio) / 2,
              img.width * ratio,
              img.height * ratio
          )

          const icon = new BMapGL.value.Icon(canvas.toDataURL(), new BMapGL.value.Size(size, size), {
            anchor: new BMapGL.value.Size(size / 2, size / 2)
          })
          resolve(icon)
        }

        img.onerror = () => {
          img.src = 'http://localhost:7090/avatar/avatar_3.jpg'
        }

        img.src = cattle.photo || 'http://localhost:7090/avatar/avatar_3.jpg'
      })
    }

    const initMap = async () => {
      try {
        BMapGL.value = await loadBMap()
        mapInstance.value = new BMapGL.value.Map('map-container', {
          enableMapClick: false,
          displayOptions: { building: true }
        })
        mapInstance.value.enableScrollWheelZoom(true)
        mapInstance.value.centerAndZoom(new BMapGL.value.Point(118.551, 31.673), 15)
      } catch (error) {
        ElMessage.error('地图初始化失败: ' + error.message)
      }
    }

    const drawTrack = async () => {
      if (!mapInstance.value || !locationData.value.length) return

      try {
        mapInstance.value.clearOverlays()

        const points = locationData.value
            .filter((item) => item.longitude && item.latitude)
            .map((item) => new BMapGL.value.Point(
                parseFloat(item.longitude),
                parseFloat(item.latitude)
            ))

        // 修改后的轨迹绘制逻辑
        if (points.length > 1) {
          const colorPalette = [
            '#FF0000', '#FF7F00', '#FFFF00',  // 红、橙、黄
            '#00FF00', '#00FFFF', '#0000FF',  // 绿、青、蓝
            '#8B00FF', '#FF1493', '#FF69B4'   // 紫、深粉、粉红
          ]

          for (let i = 0; i < points.length - 1; i++) {
            const polyline = new BMapGL.value.Polyline(
                [points[i], points[i + 1]],
                {
                  strokeColor: colorPalette[i % colorPalette.length],
                  strokeWeight: 4,
                  strokeOpacity: 0.8,
                  strokeStyle: 'solid'
                }
            )
            mapInstance.value.addOverlay(polyline)
          }
        }

        // 保持原有标记绘制逻辑不变
        points.forEach((point) => {
          const marker = new BMapGL.value.Marker(point, {
            icon: new BMapGL.value.Icon(
                `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
                <circle cx="12" cy="12" r="6" fill="#409eff" stroke="#fff" stroke-width="2"/>
              </svg>`,
                new BMapGL.value.Size(16, 16)
            )
          })
          mapInstance.value.addOverlay(marker)
        })

        // 保持原有头像标记逻辑不变
        if (points.length > 0 && currentCattle.value) {
          try {
            const icon = await createCustomIcon(currentCattle.value)
            const lastPoint = points[points.length - 1]
            const marker = new BMapGL.value.Marker3D(lastPoint, 10, {
              size: 40,
              icon,
              shape: 1,
              perspective: true
            })
            mapInstance.value.addOverlay(marker)
          } catch (error) {
            console.error('头像标记创建失败:', error)
          }
        }

        // 保持视野调整逻辑不变
        if (points.length > 0) {
          const viewport = mapInstance.value.getViewport(points)
          mapInstance.value.centerAndZoom(viewport.center, Math.min(viewport.zoom, 18))
        }
      } catch (error) {
        console.error('轨迹绘制失败:', error)
      }
    }

    const fetchLocationHistory = async (cattleId) => {
      loading.value = true
      try {
        const resp = await store.dispatch('fetchLocationHistory', {
          cattleId,
          page: currentPage.value,
          pageSize,
          token: store.state.user.token
        })

        if (resp?.status === 'success') {
          locationData.value = resp.data?.data || []
          total.value = resp.data?.total || 0
          console.log("2000" + cattleId)
          currentCattle.value = store.getters.getCattleById(cattleId)
          await nextTick()
          await drawTrack()
        }
      } catch (error) {
        ElMessage.error('获取位置数据失败: ' + error.message)
      } finally {
        loading.value = false
      }
    }

    const clickPage = (page) => {
      if (page === -1) page = currentPage.value - 1
      else if (page === -2) page = currentPage.value + 1

      if (page >= 1 && page <= totalPages.value) {
        currentPage.value = page
        const cattleId = form.searchParam || route.query.cattleId
        cattleId && fetchLocationHistory(cattleId)
      }
    }

    const handleSearch = async () => {
      if (!form.searchParam.trim()) return
      currentPage.value = 1

      try {
        let cattleId = form.searchParam
        if (!/^\d+$/.test(form.searchParam)) {
          const cattle = await store.dispatch('fetchCattleByEarTag', {
            earTag: form.searchParam,
            token: store.state.user.token
          })
          cattleId = cattle?.id
        }

        if (cattleId) {
          await fetchLocationHistory(cattleId)
        } else {
          ElMessage.error('未找到相关牛只')
        }
      } catch (error) {
        ElMessage.error('查询失败: ' + error.message)
      }
    }

    onMounted(async () => {
      await initMap()
      const cattleId = route.query.cattleId
      if (cattleId) {
        form.searchParam = cattleId
        await fetchLocationHistory(cattleId)
      }
    })

    onBeforeUnmount(() => {
      if (mapInstance.value) {
        mapInstance.value.destroy()
        mapInstance.value = null
      }
    })

    return {
      form,
      locationData,
      currentCattle,
      loading,
      currentPage,
      pages,
      totalPages,
      clickPage,
      handleSearch,
      Search
    }
  }
}
</script>

<style scoped>
.location-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.location-box {
  width: 80%;
  background-color: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

#map-container {
  height: 45vh;
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-title {
  text-align: center;
  font-size: 24px;
  margin-bottom: 1px;
  color: #409eff;
  font-weight: 600;
}

.cattle-info {
  margin: 0;
  padding: 1px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #ebeef5;
  height: 15vh;
}

.data-container {
  margin-top: 10px;
  padding: 10px;
  min-height: 40vh;
  position: relative;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.page-item {
  cursor: pointer;
  user-select: none;
}

.page-item.disabled .page-link {
  pointer-events: none;
  opacity: 0.6;
}

.page-item.active .page-link {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}

.page-link {
  color: #409eff;
  padding: 8px 16px;
  border: 1px solid #dee2e6;
  margin-left: -1px;
}

.page-link:hover {
  background-color: #f8f9fa;
}

.el-form {
  display: flex;
  justify-content: center;
}

.input-with-select {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .location-box {
    width: 95%;
    padding: 15px;
  }


  #map-container {
    height: 45vh;
  }
}

.BMap_Marker3D {
  animation: markerAppear 0.5s ease-out;
  filter: drop-shadow(0 2px 6px rgba(0, 0, 0, 0.3));
}

@keyframes markerAppear {
  0% {
    transform: scale(0);
    opacity: 0;
  }
  80% {
    transform: scale(1.1);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

</style>